package com.ruoyi.carton.controller;

import com.alibaba.excel.EasyExcel;
import com.ruoyi.carton.domain.Box;
import com.ruoyi.carton.domain.Orders;
import com.ruoyi.carton.domain.vo.ExcelVO;
import com.ruoyi.carton.domain.vo.OrdersAndBoxVO;
import com.ruoyi.carton.domain.vo.OrdersDetailVO;
import com.ruoyi.carton.domain.vo.OrdersQuery;
import com.ruoyi.carton.service.BoxService;
import com.ruoyi.carton.service.ExcelImportService;
import com.ruoyi.carton.service.OrdersService;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.bean.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@RestController
@RequestMapping("/orders")
public class OrdersController extends BaseController {

    @Autowired
    private ExcelImportService excelImportService;

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private BoxService boxService;

    /**
     * 获取订单详细信息，包括关联的箱体信息
     *
     * @param id 订单ID
     * @return 订单详细数据
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:query')")
    @Log(title = "订单查询", businessType = BusinessType.OTHER)
    @GetMapping("/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        Orders order = ordersService.getById(id);
        if (order == null) {
            return error("订单不存在");
        }

        OrdersDetailVO vo = new OrdersDetailVO();
        BeanUtils.copyProperties(order, vo);

        // 查询对应的 box 信息补充
        if (StringUtils.isNotBlank(order.getProductId())) {
            Box box = boxService.getById(order.getProductId());
            if (box != null) {
                vo.setProductName(box.getProductName());
                vo.setLength(box.getLength());
                vo.setWidth(box.getWidth());
                vo.setHeight(box.getHeight());
                vo.setOrderQuantity(box.getOrderQuantity());
                vo.setSalePrice(box.getSalePrice());
                vo.setRebate(box.getRebate());
                vo.setProfit(box.getProfit());
                vo.setArea(box.getArea());
            }
        }

        return success(vo);
    }

    /**
     * 查询订单列表（支持分页）
     *
     * @param query 查询条件
     * @return 分页数据列表
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:list')")
    @Log(title = "订单列表", businessType = BusinessType.OTHER)
    @GetMapping("/list")
    public TableDataInfo list(OrdersQuery query) {
        startPage();
        List<OrdersDetailVO> voList = ordersService.selectOrdersDetailList(query);
        return getDataTable(voList);
    }
    /**
     * 手动添加主订单信息（含订单和纸箱信息）
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:add')")
    @Log(title = "订单添加", businessType = BusinessType.INSERT)
    @PostMapping()
    public AjaxResult add(@RequestBody OrdersAndBoxVO vo) {
        try {
            ordersService.addOrderAndBox(vo);
            return AjaxResult.success("订单添加成功");
        } catch (Exception e) {
            return AjaxResult.error("添加失败：" + e.getMessage());
        }
    }

    /**
     * 使用 EasyExcel 导入订单数据Excel文件
     *
     * @param file Excel文件
     * @return 导入结果
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:import')")
    @Log(title = "订单导入", businessType = BusinessType.IMPORT)
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult importByEasyExcel(@RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return AjaxResult.error("导入文件不能为空");
        }

        try (InputStream in = file.getInputStream()) {
            // 读取Excel数据为ExcelVO列表
            List<ExcelVO> list = EasyExcel.read(in)
                    .head(ExcelVO.class)
                    .sheet()
                    .doReadSync();

            // 保存导入数据
            excelImportService.saveExcelData(list);

            return AjaxResult.success("信息导入成功，共导入 " + list.size() + " 条数据");
        } catch (IOException e) {
            return AjaxResult.error("读取文件失败：" + e.getMessage());
        } catch (RuntimeException e) {
            return AjaxResult.error("导入失败：" + e.getMessage());
        }
    }

    /**
     * 修改订单状态，并在状态变更时创建对应业务数据
     *
     * @param id 订单ID
     * @return 操作结果
     */
    @PutMapping("/{id}")
    @Log(title = "订单状态更新", businessType = BusinessType.UPDATE)
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:edit')")
    public AjaxResult updateStatusById(@PathVariable("id") String id) {
        int result = ordersService.updateStatusById(id);
        return result > 0 ? AjaxResult.success("状态更新成功") : AjaxResult.error("状态更新失败或已是最终状态");
    }

    /**
     * 修改主订单及box 信息
     */
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:edit')")
    @Log(title = "订单修改", businessType = BusinessType.UPDATE)
    @PutMapping ()
    public AjaxResult update(@RequestBody OrdersAndBoxVO vo) {
        try {
            ordersService.UpdateOrderAndBox(vo);
            return AjaxResult.success("订单修改成功");
        } catch (Exception e) {
            return AjaxResult.error("修改失败：" + e.getMessage());
        }
    }



    /**
     * 删除订单及其关联的子表数据
     *
     * @param id 订单ID
     * @return 操作结果
     */
    @DeleteMapping("/{id}")
    @PreAuthorize("@ss.hasPermi('ruoyi-carton:orders:remove')")
    @Log(title = "订单删除", businessType = BusinessType.DELETE)
    public AjaxResult delById(@PathVariable("id") String id) {
        try {
            ordersService.deleteOrderAndChildren(id);
            return AjaxResult.success("删除成功");
        } catch (Exception e) {
            return AjaxResult.error("删除失败：" + e.getMessage());
        }
    }
}
